import React                        from 'react';
import {connect}                    from "react-redux";

import Nav                          from '../../config/Navigator';
import Empty                        from '../../components/form/Empty';
import CartCount                    from '../../components/form/CartCount';
import {List}                       from './List';
import {userInfo}                   from "../../actions/active";
import {TicketHead}                 from '../main/Voucher';
import {
    edit,
    clear,
    exchange,
    loadItem
}                                   from "../../actions/cart";
import './item.scss';
import {Token} from "../../utils/Storage";

function formatTime(time, format) {
    const dateTime = new Date(time);
    const o = {
        'M+': dateTime.getMonth() + 1, // month
        'd+': dateTime.getDate(), // day
        'h+': dateTime.getHours(), // hour
        'm+': dateTime.getMinutes(), // minute
        's+': dateTime.getSeconds(), // second
        'q+': Math.floor((dateTime.getMonth() + 3) / 3), // quarter
        S: dateTime.getMilliseconds(), // millisecond
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1,
            (`${dateTime.getFullYear()}`).substr(4 - RegExp.$1.length));
    }
    for (const k in o) {
        if (new RegExp(`(${k})`).test(format)) {
            format = format.replace(RegExp.$1,
                RegExp.$1.length === 1 ? o[k] :
                (`00${o[k]}`).substr((`${o[k]}`).length));
        }
    }
    return format;
}

class Item extends List {

    _method = () => 'loadItem';

    componentWillMount(){
        if(Token.isActive()){
            this.load();
            this.props.userInfo();
        }
    }

    clear(){
        this.props.clear().then(r => {
            this.updateCount();
        });
    }

    exchange(){
        var {user, item} = this.props;
        if(!_.every(item.list, m => m.exchangeCount < m.count)){
            return this.alert('库存不足');
        }
        if(user.accumulate < this.getTotal()){
            return this.alert('积分不足');
        }
        this.props.exchange().then(r => {
            this.router.push(Nav.voucher());
        });
    }

    render(){
        var {list} = this.props.item;
        return (
            <Empty list={list} type="cart">
                <div className="c-item touch">
                    {list.map(m => {
                        var isSellout = this.isSellout(m);
                        return (
                            <div key={m.id} className="ticket">
                                <div className="tic-body" ref={`item${m.id}`}>
                                    <TicketHead item={m} className={isSellout ? 'stamp-red' : undefined}/>
                                    <div className="tic-right flex-avg">
                                        <div className="tic-detail">
                                            <div className="tic-d-name">{m.name}</div>
                                            <div className="tic-time">{m.limitPrice}</div>
                                            <div className="tic-time">兑换所需积分{m.exchangeCount * m.accumulate}</div>
                                            <div className="tic-time"><span>兑换截止：</span>{formatTime(m.expire,'yyyy-MM-dd')}</div>
                                        </div>
                                        <div
                                            onClick={() => this.toggle(m)}
                                            className={`tic-cart flex-avg${isSellout ? ' sellout' : ''}`}
                                        >
                                            <CartCount
                                                value={m.exchangeCount}
                                                target={() => this.refs[`item${m.id}`]}
                                                beforeAdd={c => this.add(m, c)}
                                                beforeMinus={c => this.minus(m, c)}
                                            />
                                            {isSellout && <div>库存不足</div>}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        );
                    })}
                </div>
                <div className="ci-footer flex-avg">
                    <div className="cif-total flex-avg">所需总积分：{this.getTotal()}</div>
                    <div className="cif-btn-c flex-avg">
                        <div className="cif-btn cif-clear" onClick={() => this.clear()}>清空</div>
                        <div className="cif-btn" onClick={() => this.exchange()}>兑换</div>
                    </div>
                </div>
            </Empty>
        );
    }

}

const mapStateToProps = state => ({
    item: state.cart.item,
    user: state.active.get,
});

export default connect(mapStateToProps, {edit, clear, exchange, loadItem, userInfo})(Item);
